package com.example.result.explore

import android.content.Intent
import android.net.Uri
import android.util.Base64
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.core.net.toUri
import androidx.core.text.isDigitsOnly
import coil.compose.AsyncImage
import coil.decode.SvgDecoder
import coil.request.ImageRequest
import com.example.result.Algorithm
import com.example.result.MainActivity
import com.example.result.R
import com.example.result.books.doSaveToFile
import com.example.result.format
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

@Composable
fun JNIExpose() {
    LazyColumn(
        Modifier
            .fillMaxWidth()
            .fillMaxHeight()
    ) {
        item {
            Text(
                text = Algorithm.hello("mylib so 调用"),
            )
            var id by remember {
                mutableStateOf(Algorithm.id.toString())
            }
            TextField(
                value = id, onValueChange =
                {
                    id = it
                    if (it.isNotEmpty() && it.isDigitsOnly()) {
                        Algorithm.id = it.toIntOrNull() ?: 0
                    }
                }, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number)
            )
        }


        item {
            HorizontalDivider(Modifier.padding(8.dp))
            var input by remember {
                mutableStateOf("")
            }
            TextField(value = input, label = {
                Text(text = "要编码的内容")
            }, onValueChange = { input = it }, isError = input.isEmpty())
            var encoderResult by remember {
                mutableStateOf<ByteArray?>(null)
            }
            Button(onClick = {
                if (input.isNotEmpty()) {
                    encoderResult =
                        Algorithm.huffmanEncode(
                            Base64.encodeToString(
                                input.toByteArray(),
                                Base64.DEFAULT
                            )
                        )
                }
            }) {
                Text(text = "huffman编码")
            }
            encoderResult?.let {
                TextField(value = it.format(), onValueChange = {}, label = {
                    Text(text = "编码结果")
                }, enabled = false)
                var decoder by remember {
                    mutableStateOf("")
                }
                Button(onClick = {
                    decoder = String(
                        Base64.decode(Algorithm.huffmanDecode(it), Base64.DEFAULT)
                    )
                }) {
                    Text(text = "解码")
                }
                if (decoder.isNotEmpty()) {
                    TextField(value = decoder, onValueChange = {}, label = {
                        Text(text = "解码结果")
                    }, enabled = false)
                }
            }
        }
        item {
            var enable by remember {
                mutableStateOf(false)
            }
            HorizontalDivider(Modifier.padding(8.dp))
            DisposableEffect(true) {
                Algorithm.redBlackST = Algorithm.createRedBlackST()
                enable = true

                onDispose {
                    enable = false

                    Algorithm.redBlackST?.let {
                        Algorithm.closeRedBlackST(it)
                    }
                    Algorithm.redBlackST = null
                }
            }
            var k by remember {
                mutableStateOf("")
            }
            var v by remember {
                mutableStateOf("")
            }
            var kv by remember {
                mutableStateOf(mapOf<String, Int>())

            }
            if (enable) {
                Text(text = "readBlackST point:${Algorithm.redBlackST}")
                Text(text = "当前键值对:$kv")
                TextField(value = k, onValueChange = { k = it }, label = { Text(text = "键") })
                TextField(
                    value = v,
                    onValueChange = {
                        v = it
                    },
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                    label = { Text(text = "值") })
                Button(onClick = {
                    val v = v.toIntOrNull() ?: 0
                    Algorithm.inertOrUpdateNodeToRedBlackST(
                        Algorithm.redBlackST!!,
                        k,
                        v
                    )
                    kv = kv.toMutableMap().apply { this[k] = v }
                }) {
                    Text(text = "插入键值对到红黑树中")
                }
                Button(onClick = {
                    Algorithm.deleteNodeToRedBlackST(
                        Algorithm.redBlackST!!,
                        k,
                    )
                    kv = kv.filterKeys { a -> a != k }
                }) {
                    Text(text = "删除键值在红黑树中")
                }
                Button(onClick = {
                    v = if (Algorithm.hasNodeToRedBlackST(Algorithm.redBlackST!!, k))
                        Algorithm.getValueToRedBlackST(Algorithm.redBlackST!!, k).toString()
                    else {
                        ""
                    }
                }) {
                    Text(text = "获取键的值")
                }
                Button(onClick = {
                    k = Algorithm.maxNodeToRedBlackST(Algorithm.redBlackST!!) ?: ""
                }) {
                    Text(text = "获取最大值")
                }
                Button(onClick = {
                    k = Algorithm.minNodeToRedBlackST(Algorithm.redBlackST!!) ?: ""
                }) {
                    Text(text = "获取最小值")
                }
                val context = LocalContext.current
                val scope = rememberCoroutineScope()
                Button(onClick = {
                    scope.launch(Dispatchers.IO) {
                        val graph = Algorithm.printRedBlackST(Algorithm.redBlackST!!).lines()
                            .filterNot { it.startsWith("#@") }.joinToString("\n")
                        val file = doSaveToFile(context, "redBlackTree.dot", graph)
                        context.startActivity(Intent(context, MainActivity::class.java).apply {
                            data = file.toUri()
                        })
                    }

                }) {
                    Text(text = "显示红黑树图")
                }
            }
        }
        item {
            var context = LocalContext.current
            AsyncImage(
                model = ImageRequest.Builder(context)
                    .data(Uri.parse("file:///android_asset/logo.svg"))
                    .decoderFactory(SvgDecoder.Factory())
                    .crossfade(true)
                    .build(),
                placeholder = painterResource(R.drawable.taiji),
                contentDescription = "svg",
//                contentScale = ContentScale.Crop,
//                modifier = Modifier.clip(CircleShape)
            )
        }
    }

}